import React, { Component } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'
import {Card, Button, Form, Input, DatePicker, Spin, Select, message} from 'antd'
import MyPageTable from '@/components/MyPageTable'
import { onTableData } from '@/utils/utils.js'
import CopyToClipboard from '@/components/CopyToClipboard'
import moment from 'moment'

const { RangePicker } = DatePicker
const { Option } = Select
import { getTimeDistance } from '@/utils/utils'

@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/queryOpeOverDueOrdersByCondition']
}))
@Form.create()
export default class BeOverdue extends Component {
  state = {
    current: 1,
    datas: {},
    yunTime: getTimeDistance('month')
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'order/PlateformChannel'
    })
    this.setState({
      datas: {
        manyOverduePeriods: '0'
      }
    })
    this.onList(1, 10, {
      manyOverduePeriods: '0'
    })
  }

  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props
    dispatch({
      type: 'order/queryOpeOverDueOrdersByCondition',
      payload: {
        pageSize,
        pageNumber,
        ...data
      }
    })
  }

  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      if (values.createDate && values.createDate.length < 1) {
        values.statementTimeStart = ''
        values.statementTimeEnd = ''
        this.setState(
          {
            datas: { ...values }
          },
          () => {
            this.onList(1, 10, { ...values })
          }
        )
      } else if (values.createDate) {
        values.statementTimeStart = moment(values.createDate[0]).format(
          'YYYY-MM-DD 00:00:00'
        )
        values.statementTimeEnd = moment(values.createDate[1]).format(
          'YYYY-MM-DD 23:59:59'
        )
        this.setState(
          {
            datas: { ...values }
          },
          () => {
            this.onList(1, 10, { ...values })
          }
        )
      } else {
        this.setState(
          {
            datas: { ...values }
          },
          () => {
            this.onList(1, 10, { ...values })
          }
        )
      }
    })
  }
  // table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current
      },
      () => {
        this.onList(e.current, 10, this.state.datas)
      }
    )
  }

  // select切换
  handleChange(value) {
    console.log(`selected ${value}`)
  }

  // 重置
  handleReset = e => {
    this.props.form.resetFields()
    this.handleSubmit(e)
  }
  confirm = () => {}
  onexport = () => {
    const { yunTime } = this.state
    const createDate = this.props.form.getFieldValue('createDate')
    if (createDate && createDate.length > 1) {
      this.props.form.validateFields((err, values) => {
        this.props.dispatch({
          type: 'order/exportOpeOverDueUserOrders',
          payload: {
            statementTimeEnd: moment(
                createDate[1]
            ).format('YYYY-MM-DD 23:59:59'),
            statementTimeStart: moment(
                createDate[0]
            ).format('YYYY-MM-DD 00:00:00'),
            pageSize:-1,
            pageNumber:-1,
            ...values
          }
        }).then(res => {
          const objectURL = URL.createObjectURL(res)
          const btn = document.createElement('a')
          const body = document.querySelector('body')
          if (body) {
            body.appendChild(btn)
          }
          btn.download = `逾期订单.xlsx`
          btn.href = objectURL
          btn.click()
          if (body) {
            body.removeChild(btn) // 删除标签
          }

          message.success('导出成功')
        })
      })

    } else {

      this.props.form.validateFields((err, values) => {
        this.props.dispatch({
          type: 'order/exportOpeOverDueUserOrders',
          payload: {
            statementTimeEnd: moment(yunTime[1]).format('YYYY-MM-DD 23:59:59'),
            statementTimeStart: moment(yunTime[0]).format('YYYY-MM-DD 00:00:00'),
            pageSize:-1,
            pageNumber:-1,
            ...values
          }
        }).then(res => {
          const objectURL = URL.createObjectURL(res)
          const btn = document.createElement('a')
          const body = document.querySelector('body')
          if (body) {
            body.appendChild(btn)
          }
          btn.download = `逾期订单.xlsx`
          btn.href = objectURL
          btn.click()
          if (body) {
            body.removeChild(btn) // 删除标签
          }

          message.success('导出成功')
        })
      })
    }
  }

  render() {
    const { conditionList, conditionTotal, PlateformList, loading } = this.props
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: conditionTotal,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }
    const columns = [
      {
        title: '订单编号',
        dataIndex: 'orderId',
        render: orderId => <CopyToClipboard text={orderId} />,
        width: '140px'
      },
      {
        title: '店铺名称',
        dataIndex: 'shopName',
        width: '140px'
      }, // {
      //   title: '渠道来源',
      //   dataIndex: 'channelName',
      //   width: '10%',
      // },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: '200px'
      }, // 接口BUG，currentPeriods字段返回始终为0
      // {
      //   title: '当前租期',
      //   dataIndex: 'currentPeriods',
      //   width: '60px',
      // },
      {
        title: '已支付期数/总期数', // dataIndex: 'currentPeriods',
        width: '110px',
        render: e => {
          return (
            <>
              <div
                style={{
                  width: 60,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap'
                }}
              >
                {e.payedPeriods}/{e.totalPeriods}
              </div>
            </>
          )
        }
      },
      {
        title: '逾期期次',
        width: '100px',
        render: e => {
          return <>{e.overduePeriods}</>
        }
      },
      {
        title: '总租金',
        width: '100px',
        render: e => {
          return <>{e.totalRentAmount}</>
        }
      },
      {
        title: '已付租金',
        width: '100px',
        render: e => {
          return <>{e.payedRentAmount}</>
        }
      },
      {
        title: '姓名',
        width: '100px',
        render: e => {
          return <>{e.realName}</>
        }
      },
      {
        title: '手机号',
        width: '130px',
        render: e => {
          return <>{e.telephone}</>
        }
      },
      {
        title: '起租时间',
        width: '120px',
        render: e => {
          return <>{e.rentStart}</>
        }
      },
      {
        title: '归还时间',
        width: '120px',
        render: e => {
          return <>{e.unrentTime}</>
        }
      },
      {
        title: '下单时间',
        dataIndex: 'placeOrderTime',
        width: '120px'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '70px',
        align: 'center',
        render: e => {
          return (
            <div style={{ textAlign: 'center' }}>
              <a
                className="primary-color"
                // onClick={() => router.push(`/Order/Details?id=${e.orderId}&settlement=settlement`)}
                href={`#/Order/BeOverdue/Details?id=${e.orderId}&settlement=settlement`}
                target="_blank"
              >
                详情
              </a>
            </div>
          )
        }
      }
    ]
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <Form.Item label="商品名称">
              {getFieldDecorator(
                'productName',
                {}
              )(<Input allowClear placeholder="请输入商品名称" />)}
            </Form.Item>
            <Form.Item label="下单人姓名">
              {getFieldDecorator(
                'userName',
                {}
              )(<Input allowClear placeholder="请输入下单人姓名" />)}
            </Form.Item>
            <Form.Item label="下单人手机号">
              {getFieldDecorator(
                'telephone',
                {}
              )(<Input allowClear placeholder="请输入下单人手机号" />)}
            </Form.Item>
            <Form.Item label="订单编号">
              {getFieldDecorator(
                'orderId',
                {}
              )(<Input allowClear placeholder="请输入订单编号" />)}
            </Form.Item>
            <Form.Item label="账单日时间">
              {getFieldDecorator('createDate', {})(<RangePicker allowClear />)}
            </Form.Item>
            <Form.Item label="逾期次数">
              {getFieldDecorator('manyOverduePeriods', { initialValue: '0' })(
                <Select style={{ width: 180 }} onChange={this.handleChange}>
                  <Option value="">全部</Option>
                  <Option value="0">逾期一次</Option>
                  <Option value="1">逾期大于一次</Option>
                </Select>
              )}
            </Form.Item>
            <div>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="button" onClick={this.handleReset}>
                  重置
                </Button>
              </Form.Item>
              <Form.Item>
                <Button onClick={this.onexport}>导出</Button>
              </Form.Item>
            </div>
          </Form>
          <Spin spinning={loading}>
            <MyPageTable
              scroll={true}
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={onTableData(conditionList)}
              columns={columns}
            />
          </Spin>
        </Card>
      </PageHeaderWrapper>
    )
  }
}
